<template>
  <div class="app-container">
    <el-row>
      <el-form :inline="true" :model="filter" class="demo-form-inline" size="mini">
        <el-row>
          <el-form-item label="最小花费">
            <el-input v-model="filter.min_cost" placeholder="过滤的最小花费" />
          </el-form-item>
          <el-form-item label="最多花费">
            <el-input v-model="filter.max_cost" placeholder="过滤的最大花费" />
          </el-form-item>
          <el-form-item label="最小收入">
            <el-input v-model="filter.min_amount" placeholder="过滤的最小花费" />
          </el-form-item>
          <el-form-item label="最多收入">
            <el-input v-model="filter.max_amount" placeholder="过滤的最大花费" />
          </el-form-item>
          <el-form-item label="最小ROI">
            <el-input v-model="filter.min_roi" placeholder="min roi" />
          </el-form-item>
          <el-form-item label="最多ROI">
            <el-input v-model="filter.max_roi" placeholder="max roi" />
          </el-form-item>
        </el-row>
        <el-row :style="showmore">
          <el-form-item label="最小收入">
            <el-input v-model="filter.min_amount" placeholder="过滤的最小花费" />
          </el-form-item>
          <el-form-item label="最多收入">
            <el-input v-model="filter.max_amount" placeholder="过滤的最大花费" />
          </el-form-item>
          <el-form-item label="最少点击">
            <el-input v-model="filter.min_click" placeholder="最少点击" />
          </el-form-item>
          <el-form-item label="最多点击">
            <el-input v-model="filter.max_click" placeholder="最多点击" />
          </el-form-item>

          <el-form-item label="最少展示">
            <el-input v-model="filter.min_display" placeholder="最少点击" />
          </el-form-item>
          <el-form-item label="最多展示">
            <el-input v-model="filter.max_display" placeholder="最多点击" />
          </el-form-item>
          <el-form-item label="汇率">
            <el-input v-model="filter.rate" placeholder="综合汇率" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="最小CPC">
            <el-input v-model="filter.min_cpc" placeholder="最小CPC" />
          </el-form-item>
          <el-form-item label="最高CPC">
            <el-input v-model="filter.max_cpc" placeholder="最高CPC" />
          </el-form-item>

          <el-form-item label="排序">
            <el-select v-model="filter.orderby" placeholder="选择默认排序">
              <el-option label="广告费" value="cost" />
              <el-option label="点击量" value="clicks" />
              <el-option label="CPC" value="cpc" />
              <el-option label="展示" value="display" />
            </el-select>
          </el-form-item>
          <el-form-item label="升序">
            <el-switch v-model="filter.reverse" />
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="filter.timerange"
              type="datetimerange"
              value-format="timestamp"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item label="立即处理">
            <el-switch v-model="filter.process" @change="handleProcessAll" />
          </el-form-item>
          <el-form-item>
            <el-button type="text" @click="handleTagMore">更多条件</el-button>
          </el-form-item>
          <!--          <el-form-item label="">-->
          <!--            <el-button size="small" type="primary"  @click="handleGetAutoReportData">直接查询</el-button>-->
          <!--          </el-form-item>-->
          <el-form-item label="">
            <el-button v-if="filter.cache_key !=='' || select_file !==''" size="small" type="warning" @click="handleReProcess">重新过滤
            </el-button>
          </el-form-item>
        </el-row>
      </el-form>

    </el-row>
    <el-row />
    <el-row :gutter="40" style="background:#fff;margin-bottom:1px;">
      <el-col :xs="24" :sm="24" :lg="4" class="card-panel-col">
        <el-upload
          class="upload-demo"
          :action="base_api"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-error="handleUploadError"
          :before-upload="handleBeforeUplaod"
          :data="filter"
          :before-remove="beforeRemove"
          :show-file-list="false"
          :on-success="handleSuccess"
          :on-exceed="handleExceed"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">上传报告文件</el-button>
        </el-upload>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="6" class="card-panel-col">
        <el-select v-model="select_file" size="mini" filterable clearable placeholder="已处理文件" @change="handleGetReportData">
          <el-option v-for="item in reportfiles" :key="item.id" :label="item.file_name+item.date_range" :value="item.id" />
        </el-select>
        <el-button size="mini" @click="handleGetReportFiles">刷新</el-button>
        <el-button v-if="chartData.length > 0" size="mini" @click="piechatVisual=true">收入比例</el-button>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="8" class="card-panel-col">
        <el-row>
          <el-col :xs="12" :sm="12" :lg="12" style="text-align: right">
            <el-select
              v-model="googleadsreportconfig_id"
              style="width:100%"
              size="mini"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="handleGetReportConfig"
              :loading="reportconfig_loading"
            >
              <el-option
                v-for="item in reportconfigs"
                :key="item.id"
                :label="item.note+item.googlemerchantconfig__website__domain"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="12" style="text-align: left">
            <el-select v-model="filter.check" style="width: 100px" size="mini" placeholder="类型">
              <el-option label="亏损" value="loss" />
              <el-option label="需要优化" value="optimize" />
              <el-option label="赚钱" value="profitable" />
              <el-option label="一般" value="normal" />
            </el-select>
            <el-button size="mini" type="primary" @click="handleGetAutoReportData">查询</el-button>
          </el-col>
        </el-row>

      </el-col>

      <el-col :xs="24" :sm="24" :lg="6" class="card-panel-col" style="float: right">
        <el-input v-model="search" size="mini" placeholder="过滤广告系列" style="float: right">
          <el-button slot="append" icon="el-icon-search" />
        </el-input>
      </el-col>
    </el-row>
    <el-row>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        border
        stripe
        height="700"
        :data="data.filter(d => !search || d.ad.toString().toLowerCase().includes(search.toLowerCase()))"
        show-summary
        style="width: 100%"
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="image"
          label="产品"
          width="100"
        >
          <template slot-scope="scope">
            <img :src="scope.row.image" width="80px" height="80px">
          </template>
        </el-table-column>
        <el-table-column prop="product_id" label="产品ID" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.website_id > 0" style="color: green;" @click="handleModifyFeed(scope.row)">{{ scope.row.product_id }}</span>
            <span v-else @click="handleModifyFeed(scope.row)">{{ scope.row.product_id }}</span>
            <el-tooltip v-if="scope.row.operation !== ''" class="item" effect="dark" :content="scope.row.reason" placement="right">
              <el-tag type="danger">{{ scope.row.operation }}</el-tag>
            </el-tooltip>

          </template>
        </el-table-column>
        <el-table-column
          prop="orders"
          sortable
          label="订单数"
          width="100"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.website_id > 0" style="color: green;" @click="handleShowOrders(scope.row)">{{ scope.row.orders }}</span>
            <span v-else>{{ scope.row.orders }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="amount"
          sortable
          label="收入"
          width="80"
        />
        <el-table-column
          prop="cost"
          sortable
          label="广告花费"
          width="110"
        >
          <template slot-scope="scope">
            {{ scope.row.cost }}
          </template>
        </el-table-column>
        <el-table-column
          prop="roi"
          sortable
          label="ROI"
          width="80"
        >
          <template slot-scope="scope">
            <el-button v-if="scope.row.website_id === ''" type="text" size="mini" @click="handleProcessSingle(scope.row)">查询转化</el-button>
            <span v-else>{{ scope.row.roi }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="cpc"
          sortable
          label="CPC"
          width="80"
        />
        <el-table-column
          prop="click_rate"
          sortable
          label="点击率"
          width="100"
        />
        <el-table-column
          prop="clicks"
          sortable
          label="点击量"
          width="100"
        />
        <el-table-column
          prop="display"
          sortable
          label="展示"
          width="100"
        />
        <el-table-column
          prop="ad"
          label="广告系列"
          width="100"
        />
        <el-table-column
          prop="adgroup"
          label="广告组"
          width="100"
        />
        <el-table-column
          prop="landing"
          label="landing"
        >
          <template slot-scope="scope">
            <a :href="scope.row.landing" target="_blank">{{ scope.row.landing }}</a>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,50,100,200,300,500]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
      <!--<el-button @click="handleShowProductModify(22)">测试</el-button>-->
    </el-row>

    <feedproductmodify
      :pst-visible="feedproductVisual"
      :website_id="website_id"
      :product_id="product_id"
      :domain="domain"
      @closePstDialog="feedproductVisual=false"
    />
    <orderdetail
      :order-static-visible="orderdetailVisual"
      :product_url="product_url"
      :website_id="website_id"
      @closeMyDialog="orderdetailVisual=false"
    />
    <!--<pie-chart :PieChartVisible="piechatVisual" :chartData="chartData" @closeMyDialog="piechatVisual=false"></pie-chart>-->
  </div>

</template>

<script>
import feedproductmodify from '@/views/orders/element/feedproductmodify'
import { GoogleAdsReportImport, GoogleAdsProcessSingle, Get_GoogleAutoReportData } from '@/api/orders/googleadsapi'
import { Get as GetReportFile } from '@/api/orders/googlereportfile'
import { Get as GetReportData } from '@/api/orders/googlereportdata'
import orderdetail from '@/views/orders/element/orderdetail'
import qs from 'qs'
// import PieChart from "@/views/orders/element/PieChart";
import { Get as GetAdsReportConfig } from '@/api/orders/googleadsreportconfig'

export default {
  components: { feedproductmodify, orderdetail },
  data() {
    return {
      current_handle: 'auto',
      googleadsreportconfig_id: '',
      reportconfig_loading: false,
      reportconfigs: [],
      chartData: [],
      piechatVisual: false,
      product_url: '',
      orderdetailVisual: false,
      page: 1,
      pagesize: 100,
      total: 0,
      select_file: '',
      reportfiles: [],
      reportfiletotal: 0,
      search: '',
      showmore: 'display:none;',
      multipleSelection: [],
      timerange: '',
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime())
            start.setHours(0, 0, 0)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天下班后',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            start.setHours(19, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近3天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '过去14天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      feedproductVisual: false,
      website_id: '',
      product_id: '',
      domain: '',
      loading: false,
      data: [],
      namelist: [],
      filter: {
        'check': 'loss',
        'cache_key': '',
        'max_roi': 0,
        'min_roi': 0,
        'min_amount': 0,
        'max_amount': 0,
        'rate': 7,
        'timerange': '',
        'reverse': false,
        'process': false,
        'orderby': 'cost',
        'min_cost': 1,
        'max_cost': 100000,
        'min_click': 0,
        'max_click': 0,
        'min_display': 0,
        'max_display': 0,
        'min_cpc': 0,
        'max_cpc': 0
      },
      fileList: [],
      base_api: '',
      history: [],
      shown: false
    }
  },
  created() {
    this.base_api = process.env.VUE_APP_BASE_API + '/orders/api/googleadsreportsave/'
    this.handleGetReportFiles()
  },
  methods: {
    handleShowProductModify(v) {
      this.website_id = v
      this.product_id = '1111'
      this.domain = '222'
      console.log('modify orinigal product id:', this.product_id)
      this.feedproductVisual = true
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      if (this.current_handle === 'handleGetAutoReportData') {
        this.handleGetAutoReportData()
      } else {
        this.handleGetReportData()
      }
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      if (this.current_handle === 'handleGetAutoReportData') {
        this.handleGetAutoReportData()
      } else {
        this.handleGetReportData()
      }
    },
    handleGetReportConfig(val) {
      if (val === '') {
        return
      }
      this.reportconfig_loading = true
      GetAdsReportConfig(null, qs.stringify({
        remote: 1,
        kw: val
      }))
        .then(response => {
          this.reportconfigs = response.data.data
          this.reportconfig_loading = false
        }).catch(err => {
          console.log(err)
          this.reportconfig_loading = false
        })
    },
    handleGetAutoReportData() {
      this.current_handle = 'handleGetAutoReportData'
      if (this.googleadsreportconfig_id === '') {
        if (this.filter.check !== 'loss' && this.filter.check !== 'optimize' && this.filter.check !== 'profitable') {
          this.$notify({
            title: '请选择正确的参数',
            message: '请选择一个报告，或者过滤条件[loss,optimize,profitable]中的一个',
            type: 'info',
            duration: 2000
          })
          return
        }
      }
      const _data = Object.assign({}, this.filter)
      if (_data.timerange) {
        _data.timerange = _data.timerange.join(',')
      } else {
        this.$notify({
          title: '必须选择时间范围',
          message: '选择7天内最好',
          type: 'info',
          duration: 2000
        })
        return
      }

      _data.page = this.page
      _data.pagesize = this.pagesize
      _data.googleadsreportconfig_id = this.googleadsreportconfig_id
      this.loading = true
      Get_GoogleAutoReportData(_data)
        .then(response => {
          this.loading = false
          this.data = response.data.data
          this.chartData = response.data.summerdata
          this.total = response.data.total
        }).catch(err => {
          this.loading = false
          console.log(err)
        })
    },
    handleGetReportData() {
      this.current_handle = 'handleGetReportData'
      const _data = Object.assign({}, this.filter)
      _data.googlereportfile_id = this.select_file
      _data.page = this.page
      _data.pagesize = this.pagesize
      console.log(this.pagesize)
      this.loading = true
      GetReportData('', qs.stringify(_data))
        .then(response => {
          this.loading = false
          this.data = response.data.data
          this.chartData = response.data.summerdata
          this.total = response.data.total
        }).catch(err => {
          this.loading = false
          console.log(err)
        })
    },
    handleGetReportFiles() {
      GetReportFile('', qs.stringify({
        latest: 1
      }))
        .then(response => {
          this.reportfiles = response.data.data
          this.reportfiletotal = response.data.total
        }).catch(err => {
          console.log(err)
        })
    },
    handleTagMore() {
      if (this.shown) {
        this.showmore = 'display:none;'
      } else {
        this.showmore = 'display:inline-block;'
      }
      this.shown = !this.shown
    },
    handleProcessAll(val) {
      if (val) {
        this.base_api = process.env.VUE_APP_BASE_API + '/orders/api/googleadsreportimport/'
      } else {
        this.base_api = process.env.VUE_APP_BASE_API + '/orders/api/googleadsreportsave/'
      }
      console.log(1, this.base_api)
    },
    handleReProcess() {
      if (this.filter.cache_key !== '') {
        this.loading = true
        const _data = Object.assign({}, this.filter)
        if (_data.timerange) {
          _data.timerange = _data.timerange.join(',')
        }
        GoogleAdsReportImport(_data).then(response => {
          this.loading = false
          this.data = response.data.data
          this.filter.cache_key = response.data.cache_key
          this.namelist = response.data.namelist
          this.$notify({
            title: '处理完成',
            message: '已经处理完毕数据',
            type: 'success',
            duration: 2000
          })
        })
      } else {
        this.handleGetReportData()
      }
    },
    handleProcessSingle(row) {
      const _data = Object.assign({}, row)
      if (this.filter.timerange) {
        _data['timerange'] = this.filter.timerange.join(',')
      } else {
        _data['timerange'] = ''
      }
      _data['rate'] = this.filter.rate
      GoogleAdsProcessSingle(_data).then(response => {
        this.loading = false
        row.orders = response.data.data.orders
        row.amount = response.data.data.amount
        row.website_id = response.data.data.website_id
        row.product_id = response.data.data.product_id
        row.image = response.data.data.image
        row.roi = response.data.data.roi

        this.$notify({
          title: '处理完成',
          message: '已经处理完毕数据',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleModifyFeed(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
      if (row.website_id) {
        this.website_id = parseInt(row.website_id)
        this.product_id = row.product_id
        this.domain = row.domain
        this.feedproductVisual = true
      }
    },
    handleShowOrders(row) {
      if (row.website_id) {
        this.website_id = parseInt(row.website_id)
        this.product_url = row.landing
        this.orderdetailVisual = true
        console.log('shown')
      }
    },
    handleSelectionChange(val) {
      // this.multipleSelection = []
      // val.forEach(item => {
      //   if (item.product_id) {
      //     this.multipleSelection.push(item.product_id)
      //   }
      // })
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleUploadError(err, file, fileList) {
      this.$notify({
        title: '失败',
        message: err,
        type: 'success',
        duration: 2000
      })
    },
    handleBeforeUplaod(file) {
      this.loading = true
      this.data = []
      this.namelist = []
      this.filter.cache_key = ''
    },
    handleExceed(files, fileList) {
      this.loading = true
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSuccess(response, file, fileList) {
      this.loading = false
      if (this.filter.process) {
        this.data = response.data.data
        this.filter.cache_key = response.data.cache_key
        this.namelist = response.data.namelist
        this.$notify({
          title: '处理完成',
          message: '已经处理完毕数据',
          type: 'success',
          duration: 2000
        })
      } else {
        this.$notify({
          title: '处理完成',
          message: response.msg,
          type: 'success',
          duration: 2000
        })
      }
    }
  }
}
</script>

<style scoped>

</style>
